package org.eda.actividad4;

public class BinSearchTree<T> {
	private BinaryTreeNode<T> root;
	private int count;
	
	public BinSearchTree() {
		this.root = null;
		this.count = 0;
	}
	
	public boolean isEmpty() {
		return root == null;
	}
	
	public void add(T elem) {
		BinaryTreeNode<T> temp = new BinaryTreeNode<T>(elem);
		Comparable<T> comparableElement = (Comparable<T>) elem;
		
		if(this.isEmpty()) {
			root = temp;
		}
		else
		{
			BinaryTreeNode<T> current = root;
			boolean added = false;
			
			while(!added) {
				if(comparableElement.compareTo(current.element) < 0) {
					if(current.left == null) {
						current.left = temp;
						added = true;
					}
					else
					{
						current = current.left;
					}
				}
				else
				{
					if(current.right == null) {
						current.right = temp;
						added = true;
					}
					else
					{
						current = current.right;
					}
				}
			}
		}
		count++;
	}
	
	public boolean contains(T elem) {
		return find(elem, root);
	}
	
	private boolean find(T elem, BinaryTreeNode<T> root) {
		Comparable<T> comparableElement = (Comparable<T>) elem;
		BinaryTreeNode<T> current = root;
		boolean enc = false;
		
		if(current != null)
		{
			if(comparableElement.compareTo(current.element) == 0) {
				enc = true;
			}
			else
			{
				if(comparableElement.compareTo(current.element) < 0) {
					enc = this.find(elem, current.left);
				}
				else
				{
					enc = this.find(elem, current.right);
				}
			}
		}
		return enc;
	}
}
